package tuling.netty.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import tuling.netty.codec.domain.CodecUser;
import tuling.netty.codec.utils.ProtostuffUtil;

/**
 * @author RenGaoshuai
 * @date 2023/12/4 10:24
 * @description
 */
public class CodecClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //编码解码器
//                             pipeline.addLast("stringencode",new StringEncoder());
//                            pipeline.addLast("stringdecode",new StringDecoder());
//                            //对象类型
                            pipeline.addLast("objectencode", new ObjectEncoder());
                            pipeline.addLast("objectdecode", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                            //自定义对象编解码器
                            pipeline.addLast(new CodecClientHandler());
                        }
                    });


            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();
            System.out.println("client start success");

            String stringmessage = "我是客户端";
            CodecUser codecUser = new CodecUser("111", "客户端", 210);
            cf.channel().writeAndFlush( Unpooled.copiedBuffer(ProtostuffUtil.serializer(codecUser)));

            cf.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("client interrupted exception");
        } finally {
            group.shutdownGracefully();
        }

    }
}
